//
//  MCPullMenuViewController.m
//  TLYLSF
//
//  Created by MC on 2017/6/7.
//  Copyright © 2017年 MC. All rights reserved.
//

#import "MCPullMenuViewController.h"
#import "MCCollectionViewFlowLayout.h"
#import "MCPullMenuCollectionViewCell.h"
#import "MCPullMenuTableViewCell.h"
#import "MCMineCellModel.h"
#import "MCPullMenuModel.h"
#import "MCDataTool.h"

#define COLOR_BLUE  [UIColor colorWithRed:85/255.0 green:153/255.0 blue:229/255.0 alpha:1.0]
#define HEIGHT_MENU 300
#define WIDTH_LEFT  108

@interface MCPullMenuViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UITableViewDelegate,
UITableViewDataSource,
UIAlertViewDelegate
>

/**左边的tableView 一级菜单*/
@property(nonatomic,strong) UITableView *tableView;

/**左边的collectionView 级菜单*/
@property(nonatomic,strong) UICollectionView * collectionView;

/**UITableView的数据源*/
@property(nonatomic,strong) NSMutableArray <SectionModel *>* marr_Section;

/**UICollectionView的数据源*/
@property(nonatomic,strong) NSMutableArray <CollectionModel *>* marr_Collection;

/**玩法一级数组《playType》*/
@property(nonatomic,strong) NSMutableArray * marr_Left;



/**玩法二级字典组*/
@property(nonatomic,strong) NSMutableDictionary * mdic_Right;

/***/
@property(nonatomic,strong) NSDictionary   * dic_CZHelper;

/***/
@property(nonatomic,strong) NSDictionary   * dic_CZ;

/***/
@property(nonatomic,strong) NSDictionary   * dic_WFHelper;

@end

@implementation MCPullMenuViewController
#pragma mark-life
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self  checkOutLotteryId];
    [self  updatePreferredContentSizeWithTraitCollection:self.traitCollection];
    [self  setProperty];
    [self  createUI];
    [self  loadData];
}

#pragma mark-校验传过来的彩种ID是否正确
-(void)checkOutLotteryId{
    if (!_lotteriesTypeModel.categoryID||_lotteriesTypeModel.categoryID.length<1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你没有传入彩种ID" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alert.alertViewStyle = UIAlertViewStyleDefault;
        [alert show];
        return;
    }else{
        
        if ([self.dic_CZHelper objectForKey:_lotteriesTypeModel.categoryID]) {
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有找到该彩种" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            alert.alertViewStyle = UIAlertViewStyleDefault;
            [alert show];
            return;
        }
    }
}
#pragma mark==================setProperty======================
-(void)setProperty{
    _marr_Left=[[NSMutableArray alloc]init];
    _marr_Right=[[NSMutableArray alloc]init];
    _mdic_Right=[[NSMutableDictionary alloc]init];
    _marr_Section=[[NSMutableArray alloc]init];
    _marr_Collection=[[NSMutableArray alloc]init];
    
    self.view.backgroundColor = COLOR_BLUE;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title=NSStringFromClass([self class]);
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
}

#pragma mark==================createUI======================
-(void)createUI{
    
    [self.view addSubview:self.tableView];
    self.tableView.frame=CGRectMake(0, 0, WIDTH_LEFT, HEIGHT_MENU);
    
    [self.view addSubview:self.collectionView];
    self.collectionView.frame=CGRectMake(WIDTH_LEFT+1, 0, G_SCREENWIDTH-WIDTH_LEFT, HEIGHT_MENU);
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark==================loadData======================
-(void)loadData{
    /*
     *  根据传入的ID  获取彩种信息
     */
    NSDictionary * czInfo=[self.dic_CZHelper objectForKey:_lotteriesTypeModel.categoryID];
    MCCZHelperModel * modelCZ=[MCCZHelperModel mj_objectWithKeyValues:czInfo];
    NSLog(@"%@-%@-%@-%@",modelCZ.tag,modelCZ.type,modelCZ.name,modelCZ.logo);
    
    /*
     * 根据type【esf】找出玩法
     */
    //    玩法一级数组
    _marr_Left=[[self.dic_WFHelper objectForKey:modelCZ.type] objectForKey:@"playType"];
    
    
    
    
    
    
    /*
     * 如果传入玩法ID  就选玩法ID 没有就默认选中第一级玩法的第一个
     */
    NSIndexPath *indexPath;
    int i=0,j=0;
    if (_lotteriesTypeModel.typeId.length>0) {
        for (NSDictionary * dic in _marr_Left) {
            if ([dic[@"typeId"] isEqualToString:_lotteriesTypeModel.typeId]) {
                indexPath= [NSIndexPath indexPathForRow:i inSection:0];
                j=i;
            }
            i++;
        }
    }
    if (!indexPath) {
        indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    }
    
    
    
    
    
    
    
    
    
    
    
    
    //    玩法二级字典组
    _mdic_Right=[[self.dic_WFHelper objectForKey:modelCZ.type] objectForKey:@"playMethod"];
    //默认选中第一级玩法的第j个
    MC_PlayType_Model * modelF = [MC_PlayType_Model mj_objectWithKeyValues:_marr_Left[j]];
    //玩法二级数组
    _marr_Right=[_mdic_Right objectForKey:modelF.typeId];
    
    //构建左侧一级菜单
    [self createMarr_Section];
    
    //构建右侧二级菜单
    [self createMarr_Collection];
    
    
    /*
     * 构建完UI  再选中
     */
    
    [_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone]; //  设置默认选中的行
    MCPullMenuTableViewCell *ex_cell = [_tableView cellForRowAtIndexPath:indexPath];
    [ex_cell setSelected:YES animated:YES];  // 使cell 的 状态设置为选中状态
    
    
    
    
    /*
     * 如果传入玩法ID  就选玩法ID  没有就默认选中第二级玩法的第一个
     */
    if (_lotteriesTypeModel.playOnlyNum.length>1) {
        int k=0;
        for (NSDictionary * dic in _marr_Right) {
            if ([dic[@"playOnlyNum"] isEqualToString:_lotteriesTypeModel.playOnlyNum]) {
                [self.collectionView  selectItemAtIndexPath:[NSIndexPath indexPathForItem:k inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
            }
            k++;
        }
        
    }else{
        [self.collectionView  selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    }
    
}

#pragma mark-构建左侧一级菜单
-(void)createMarr_Section{
    
    [_marr_Section removeAllObjects];
    NSMutableArray * marr=[[NSMutableArray alloc]init];
    for(int i=0 ;i<_marr_Left.count; i++){
        CellModel* model =[[CellModel alloc]init];
        model.reuseIdentifier = NSStringFromClass([MCPullMenuTableViewCell class]);
        model.className=NSStringFromClass([MCPullMenuTableViewCell class]);
        model.height = [MCPullMenuTableViewCell computeHeight:nil];
        model.selectionStyle=UITableViewCellSelectionStyleNone;
        model.accessoryType=UITableViewCellAccessoryNone;
        /*
         * 传递参数
         */
        model.userInfo = [_marr_Left objectAtIndex:i];
        [marr addObject:model];
    }
    SectionModel *model0=[SectionModel sectionModelWithTitle:@"" cells:marr];
    model0.headerhHeight=13;
    model0.footerHeight=0.0001;
    [_marr_Section addObject:model0];
    [self.tableView reloadData];
}

#pragma mark-构建右侧二级菜单
-(void)createMarr_Collection{
    [_marr_Collection    removeAllObjects];
    for (int i=0; i<_marr_Right.count; i++) {
        CollectionModel * model0=[[CollectionModel alloc]init];
        model0.header_size=CGSizeMake(G_SCREENWIDTH, 18);
        model0.item_size=CGSizeMake((G_SCREENWIDTH-WIDTH_LEFT-50)/2.0, 35);
        model0.section_color=COLOR_BLUE;
        model0.section_Edge=UIEdgeInsetsMake(0, 20, 0, 20);
        model0.interitemSpacing=0.000001;
        model0.lineSpacing=0.00001;
        model0.isHaveHeader=YES;
        model0.id_dentifier=NSStringFromClass([MCPullMenuCollectionViewCell class]);
        [_marr_Collection addObject:model0];
    }
    
    [self.collectionView reloadData];
}

+(MCBasePWFModel*)Get_DefaultDicWithID:(NSString *)lotteryId{
    /*
     *  根据传入的ID  获取彩种信息
     */
    NSDictionary * dic_CZHelper = [MCDataTool MC_GetDic_CZHelper];
    NSDictionary * czInfo=[dic_CZHelper objectForKey:lotteryId];
    MCCZHelperModel * modelCZ=[MCCZHelperModel mj_objectWithKeyValues:czInfo];
    
    /*
     * 根据type找出玩法
     */
    NSDictionary * dic_WF = [MCDataTool MC_GetDic_WFHelper];
    //    玩法一级数组
    NSMutableArray *  marr_Left=[[dic_WF objectForKey:modelCZ.type] objectForKey:@"playType"];
    //    玩法二级字典组
    NSMutableDictionary * mdic_Right=[[dic_WF objectForKey:modelCZ.type] objectForKey:@"playMethod"];
    
    /*
     * 默认选中第一级玩法的第一个
     */
    MC_PlayType_Model * modelF = [MC_PlayType_Model mj_objectWithKeyValues:marr_Left[0]];
    NSMutableArray * marr_Right=[mdic_Right objectForKey:modelF.typeId];
    MCBasePWFModel *baseWFmodel = [MCBasePWFModel mj_objectWithKeyValues:[marr_Right objectAtIndex:0]];
    baseWFmodel.czID=lotteryId;
    return baseWFmodel;
}


-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = COLOR_BLUE;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    if ([cm.className isEqualToString:NSStringFromClass([MCPullMenuTableViewCell class])]) {
        MCPullMenuTableViewCell *ex_cell=(MCPullMenuTableViewCell *)cell;
        ex_cell.dataSource=cm.userInfo;
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MC_PlayType_Model * modelF = [MC_PlayType_Model mj_objectWithKeyValues:_marr_Left[indexPath.row]];
    _marr_Right=[_mdic_Right objectForKey:modelF.typeId];
    [self createMarr_Collection];
    
}

#pragma ===========================================
#pragma mark-collectionView
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        
        //创建一个layout布局类
        MCCollectionViewFlowLayout * layout = [[MCCollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView=[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor=COLOR_BLUE;
        _collectionView.dataSource=self;
        _collectionView.delegate=self;
        [_collectionView registerClass:[MCPullMenuCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([MCPullMenuCollectionViewCell class])];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
        
    }
    return _collectionView;
}


#pragma mark <UICollectionViewDataSource> 代理相关
//设置headerView和footerView的
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        return [self MC_collectionView:collectionView forIndexPath:indexPath];
    }
    
    return nil ;
}

//UICollectionViewHeader
-(UICollectionReusableView*)MC_collectionView:(UICollectionView*)collectionView forIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView * header= [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
    header.backgroundColor=[UIColor clearColor];
    return header;
}
//设置section头视图的参考大小，与tableheaderview类似
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(G_SCREENWIDTH, 18);
}
//设置section的颜色
- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout colorForSectionAtIndex:(NSInteger)section{
    return COLOR_BLUE;
}
//设置item的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionModel * model=self.marr_Collection[indexPath.section];
    return model.item_size;
}
//设置section的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    CollectionModel * model=self.marr_Collection[section];
    return model.section_Edge;
}
//两个cell之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    CollectionModel * model=self.marr_Collection[section];
    return model.interitemSpacing;
}
//两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    CollectionModel * model=self.marr_Collection[section];
    return model.lineSpacing;
}

//numberOfItemsInSection
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.marr_Collection.count == 0) {
        return 0;
    }
    CollectionModel * model=self.marr_Collection[section];
    if ([model.id_dentifier isEqualToString:NSStringFromClass([MCPullMenuCollectionViewCell class])]) {
        return self.marr_Collection.count;
    }
    return 0;
}

//numberOfSections
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//UICollectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell*  cell=nil;
    CollectionModel * model=self.marr_Collection[indexPath.section];
    if (model.id_dentifier) {
        cell =[collectionView dequeueReusableCellWithReuseIdentifier:model.id_dentifier forIndexPath:indexPath];
    }
    if ([model.id_dentifier isEqualToString:NSStringFromClass([MCPullMenuCollectionViewCell class])]) {
        
        MCPullMenuCollectionViewCell *ex_cell=(MCPullMenuCollectionViewCell *)cell;
        ex_cell.dataSource=[_marr_Right objectAtIndex:indexPath.row];
        
    }
    return cell;
}

//didSelectItemAtIndexPath
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CollectionModel * model=self.marr_Collection[indexPath.section];
    if ([model.id_dentifier isEqualToString:NSStringFromClass([MCPullMenuCollectionViewCell class])]) {
        if ([self.delegate respondsToSelector:@selector(selectLotteryKindWithTag:)]) {
            MCBasePWFModel *baseWFmodel = [MCBasePWFModel mj_objectWithKeyValues:[_marr_Right objectAtIndex:indexPath.row]];
            [self.delegate selectLotteryKindWithTag:baseWFmodel];
            [self dismissViewControllerAnimated:YES completion:NULL];
        }
    }
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}

- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
    
    [super willTransitionToTraitCollection:newCollection withTransitionCoordinator:coordinator];
    [self updatePreferredContentSizeWithTraitCollection:newCollection];
    
}

#pragma mark-更新高度
- (void)updatePreferredContentSizeWithTraitCollection:(UITraitCollection *)traitCollection{
    
    self.preferredContentSize = CGSizeMake(G_SCREENWIDTH, HEIGHT_MENU);
    
}
- (void)dealloc{
    
    NSLog(@"updatePreferredContentSizeWithTraitCollection----dealloc");
}

#pragma mark-懒加载
-(NSDictionary *)dic_CZ{
    if (!_dic_CZ) {
        _dic_CZ = [MCDataTool MC_GetDic_CZ];
    }
    return _dic_CZ;
}

-(NSDictionary *)dic_CZHelper{
    if (!_dic_CZHelper) {
        _dic_CZHelper = [MCDataTool MC_GetDic_CZHelper];
    }
    return _dic_CZHelper;
}
-(NSDictionary *)dic_WFHelper{
    if (!_dic_WFHelper) {
        _dic_WFHelper = [MCDataTool MC_GetDic_WFHelper];
    }
    return _dic_WFHelper;
}


@end




























